//
//  DeliveryDetailsViewController.m
//  Logistics
//
//  Created by hy002 on 2018/1/16.
//  Copyright © 2018年 HUYU. All rights reserved.
//

#import "DeliveryDetailsViewController.h"
#import "PersonalHomePageViewController.h"

static NSString *cellPath = @"DeliveryDetailsCell";
@interface DeliveryDetailsViewController ()<UITableViewDelegate,UITableViewDataSource>
{
    UIImage *logoimage;
}
@property (nonatomic, strong)UITableView *tableview;
@property (nonatomic, strong)HallModel *model;

@end

@implementation DeliveryDetailsViewController
- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    NSNotificationCenter * center = [NSNotificationCenter defaultCenter];
    [center addObserver:self selector:@selector(callPhonesNotifice:) name:@"callPhones" object:nil];
}

- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:@"callPhones" object:nil];
}


- (void)callPhonesNotifice:(NSNotification *)center
{
    NSString *timeStr = [center object];
    Student *stu = [Student studentWith:_model.userheadImg name:_model.username Phone:_model.userphone Times:timeStr];
    BOOL isInsert = [StudentFMDNManager addStudent:stu];

    if (isInsert) {
        NSLog(@"插入成功");
    } else {
        NSLog(@"插入失败");
    }
}
- (void)viewDidLoad {
    [super viewDidLoad];
    [self creatUI];
    [self requestSuppHallList];
    
}

- (void)creatUI
{
    self.navigationItem.title = @"货源信息";
    self.navigationController.navigationBar.translucent = NO;
    self.view.backgroundColor = BacksColor;
    self.tableview = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT-STA_NAV_HEIGHT-55*displaywidth-SCREER_HeiX) style:UITableViewStylePlain];
    _tableview.backgroundColor = BacksColor;
    _tableview.delegate = self;
    _tableview.dataSource = self;
    _tableview.separatorStyle = UITableViewCellSeparatorStyleNone;
    [self.view addSubview:_tableview];
    
    UIButton *cancelBtn = [ZCControl createButtonWithFrame:CGRectMake(15*displaywidth, SCREEN_HEIGHT-STA_NAV_HEIGHT-55*displayheight-SCREER_HeiX, SCREEN_WIDTH/2-22.5*displaywidth, 45*displayheight) ImageName:nil Target:self Action:@selector(shareAction) Title:@"分享" Font:16.0];
    cancelBtn.backgroundColor = RGB(87, 107, 149);
    [cancelBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    cancelBtn.layer.cornerRadius = 5;
    cancelBtn.layer.masksToBounds = YES;
    [self.view addSubview:cancelBtn];
    
    UIButton *backBtn = [ZCControl createButtonWithFrame:CGRectMake(SCREEN_WIDTH/2+7.5*displaywidth, SCREEN_HEIGHT-STA_NAV_HEIGHT-55*displayheight-SCREER_HeiX, SCREEN_WIDTH/2-22.5*displaywidth, 45*displayheight) ImageName:nil Target:self Action:@selector(callAction) Title:@"电话" Font:16.0];
    backBtn.backgroundColor = YellowColor;
    [backBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    backBtn.layer.cornerRadius = 5;
    backBtn.layer.masksToBounds = YES;
    [self.view addSubview:backBtn];
    
}

//分享
- (void)shareAction
{
//    https://new.wuliu.xin/lobby/detail?id=47
    if (![LTools storageForKey:SERVER_IsLogin])
    {
        [LTools showMBProgressWithText:@"请先登录" addToView:self.view];
        return;
    }
    UserAccountModel *model = [UserAccountModel shareMange];
    ShareManager *manager = [ShareManager shareToManager];
    manager.title = @"专线网";
    NSString *startStr = [NSString stringWithFormat:@"%@%@%@",_model.shipmentcity,_model.shipmentdistrict,_model.shipmentname];
    NSString *stopStr = [NSString stringWithFormat:@"%@%@%@",_model.destinationCity,_model.destinationDistrict,_model.destinationname];
    manager.descriptionStr = [NSString stringWithFormat:@"%@发布了%@-%@的货物信息...",_model.username,startStr,stopStr];
    manager.imgUrl = @"logo3x60";
    manager.logoimgUrl = nil;
    if (logoimage)
    {
        manager.logoimgUrl = logoimage;
    }
    manager.webUrl = [NSString stringWithFormat:@"https://new.wuliu.xin/lobby/detail?id=%@&inviteUserId=%ld",_model.ID,model.ID];
}

//电话
- (void)callAction
{
    [[UIApplication sharedApplication]openURL:[NSURL URLWithString:[NSString stringWithFormat:@"tel://%@",_model.userphone]]];

}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 3;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (section == 1)
    {
        return 3;
    }
    return 1;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
    if (!cell)
    {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:cellPath];
    }
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    cell.backgroundColor = [UIColor whiteColor];
    if (!_model)
    {
        return cell;
    }
    if (indexPath.section == 0)
    {
        UILabel *typeLab = [ZCControl createLabelWithFrame:CGRectMake(15*displaywidth, 5*displaywidth, SCREEN_WIDTH/2, 40*displaywidth) Font:18.0 Text:[NSString stringWithFormat:@"【%@】",_model.cargoTagname] Color:[UIColor blackColor]];
        typeLab.font = [UIFont fontWithName:@"Helvetica-Bold" size:18.0];

        [cell.contentView addSubview:typeLab];
        UILabel *timeLab = [ZCControl createLabelWithFrame:CGRectMake(150*displaywidth, 5*displaywidth, SCREEN_WIDTH-165*displaywidth, 40*displaywidth) Font:14.0 Text:[NSString stringWithFormat:@"发货时间：%@%@",_model.shipmentDay,_model.shipmentTime] Color:ThemeColor];
        timeLab.textAlignment = NSTextAlignmentRight;
        [cell.contentView addSubview:timeLab];
        UIView *lineAview = [[UIView alloc] initWithFrame:CGRectMake(15*displaywidth, 49*displaywidth, SCREEN_WIDTH-30*displaywidth, 1*displaywidth)];
        lineAview.backgroundColor = LinesColor;
        [cell.contentView addSubview:lineAview];
        
    }
    else if (indexPath.section == 1)
    {
        NSArray *imgAry = @[@"hy_icon01",@"hy_icon02",@"synav3h"];
        UIImageView *imgView = [ZCControl createImageViewWithFrame:CGRectMake(15*displaywidth, 15*displaywidth, 20*displaywidth, 20*displaywidth) ImageName:imgAry[indexPath.row]];
        imgView.contentMode = UIViewContentModeScaleAspectFit;
        [cell.contentView addSubview:imgView];
        UIView *lineBview = [[UIView alloc] initWithFrame:CGRectMake(15*displaywidth, 49*displaywidth, SCREEN_WIDTH-30*displaywidth, 1*displaywidth)];
        lineBview.backgroundColor = LinesColor;
        [cell.contentView addSubview:lineBview];
        if (indexPath.row == 0)
        {
            CGFloat W = 0;
            UILabel *startLab = [ZCControl createLabelWithFrame:CGRectMake(45*displaywidth, 5*displaywidth, 145*displaywidth, 40*displaywidth) Font:14.0 Text:[NSString stringWithFormat:@"%@%@%@",_model.shipmentcity,_model.shipmentdistrict,_model.shipmentname] Color:BlaTitColor];
            startLab.font = [UIFont fontWithName:@"Helvetica-Bold" size:14.0];
            CGRect bound1 = [startLab.text boundingRectWithSize:CGSizeMake(SCREEN_WIDTH, 40*displaywidth) options:NSStringDrawingUsesLineFragmentOrigin attributes:[NSDictionary dictionaryWithObject:NormalFontWithSize(14.0+fontScale) forKey:NSFontAttributeName] context:nil];
            startLab.frame = CGRectMake(45*displaywidth, 5*displaywidth, bound1.size.width+5*displaywidth, 40*displaywidth);
            W += (bound1.size.width+50*displaywidth);
            
            [cell.contentView addSubview:startLab];
            UIImageView *imgBView = [ZCControl createImageViewWithFrame:CGRectMake(W, 15*displaywidth, 30*displaywidth, 20*displaywidth) ImageName:@"zxli_icon01"];
            imgBView.contentMode = UIViewContentModeScaleAspectFit;
            [cell.contentView addSubview:imgBView];
            W+=30*displaywidth;
            UILabel *stopLab = [ZCControl createLabelWithFrame:CGRectMake(W, 5*displaywidth, SCREEN_WIDTH-W-10*displaywidth, 40*displaywidth) Font:14.0 Text:[NSString stringWithFormat:@"%@%@%@",_model.destinationCity,_model.destinationDistrict,_model.destinationname] Color:BlaTitColor];
            stopLab.font = [UIFont fontWithName:@"Helvetica-Bold" size:14.0];
            [cell.contentView addSubview:stopLab];
        }
        else if (indexPath.row == 1)
        {
            NSString *volStr = _model.cargoType;
            if (![_model.weight isEqualToString:@""])
            {
                volStr = [volStr stringByAppendingString:[NSString stringWithFormat:@"/%@吨",_model.weight]];
            }
            if (![_model.volume isEqualToString:@""])
            {
                volStr = [volStr stringByAppendingString:[NSString stringWithFormat:@"/%@立方",_model.volume]];
            }
            UILabel *volumeLab = [ZCControl createLabelWithFrame:CGRectMake(45*displaywidth, 5*displaywidth, SCREEN_WIDTH-60*displaywidth, 40*displaywidth) Font:15.0 Text:volStr Color:YellowColor];
            [cell.contentView addSubview:volumeLab];
        }
        else
        {
            lineBview.hidden = YES;
            NSString *lenStr = @"需不限长度";
            if (![_model.length isEqualToString:@""])
            {
                lenStr = string(@"需", _model.length);
                lenStr = string(lenStr, @"米");
            }
            if (![_model.truckType isEqualToString:@""])
            {
                lenStr = [lenStr stringByAppendingString:[NSString stringWithFormat:@"/%@",_model.truckType]];
            }
            if ([_model.baffle integerValue] == 1)
            {
                lenStr = [lenStr stringByAppendingString:@"/尾板"];
            }
            UILabel *lentnLab = [ZCControl createLabelWithFrame:CGRectMake(45*displaywidth, 5*displaywidth, SCREEN_WIDTH-60*displaywidth, 40*displaywidth) Font:15.0 Text:lenStr Color:ThemeColor];
            [cell.contentView addSubview:lentnLab];
            UIView *backV = [[UIView alloc] initWithFrame:CGRectMake(15*displaywidth, 50*displaywidth, SCREEN_WIDTH-30*displaywidth, 35*displaywidth)];
            backV.backgroundColor = RGB(235, 235, 242);
            backV.layer.cornerRadius = 5;
            backV.layer.masksToBounds = YES;
            [cell.contentView addSubview:backV];
            
            UILabel *contLab = [ZCControl createLabelWithFrame:CGRectMake(15*displaywidth, 0, SCREEN_WIDTH-60*displaywidth, 35*displaywidth) Font:13.0 Text:string(@"备注：", _model.remark) Color:RGB(87, 107, 149)];
            CGRect bounds = [contLab.text boundingRectWithSize:CGSizeMake(SCREEN_WIDTH-60*displaywidth, 2000*displaywidth) options:NSStringDrawingUsesLineFragmentOrigin attributes:[NSDictionary dictionaryWithObject:NormalFontWithSize(13.0+fontScale) forKey:NSFontAttributeName] context:nil];
            CGFloat h = 85*displaywidth;
            if (bounds.size.height > 30*displaywidth)
            {
                backV.frame = CGRectMake(15*displaywidth, 50*displaywidth, SCREEN_WIDTH-30*displaywidth, bounds.size.height+10*displaywidth);
                contLab.frame = CGRectMake(15*displaywidth, 0, SCREEN_WIDTH-60*displaywidth, bounds.size.height+10*displaywidth);
                h = 50*displaywidth+bounds.size.height+10*displaywidth;
            }
            [backV addSubview:contLab];
            if ([_model.remark isEqualToString:@""])
            {
                contLab.textAlignment = NSTextAlignmentCenter;
                contLab.text = @"备注：都已经交代完啦！";
            }
            NSString *str = [self timeIntervalFromLastTime:_model.createDtm lastTimeFormat:@"yyyy-MM-dd HH:mm:ss"];
            UILabel *timeBLab = [ZCControl createLabelWithFrame:CGRectMake(15*displaywidth, h*displaywidth, 120*displaywidth, 30*displaywidth) Font:14.0 Text:str Color:RGB(87, 107, 149)];
            [cell.contentView addSubview:timeBLab];
            
            UILabel *priceLab = [ZCControl createLabelWithFrame:CGRectMake(SCREEN_WIDTH-200*displaywidth, h*displaywidth, 185*displaywidth, 30*displaywidth) Font:14.0 Text:[NSString stringWithFormat:@"运价：%@元左右",_model.price] Color:RGB(255, 51, 51)];
            priceLab.textAlignment = NSTextAlignmentRight;
            [cell.contentView addSubview:priceLab];
        }
    }
    else
    {
        cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
        cell.backgroundColor = BacksColor;
        UIView *whiteView = [[UIView alloc] initWithFrame:CGRectMake(0, 10*displaywidth, SCREEN_WIDTH, 70*displaywidth)];
        whiteView.backgroundColor = [UIColor whiteColor];
        [cell.contentView addSubview:whiteView];
        UIImageView *faceView = [ZCControl createImageViewWithFrame:CGRectMake(15*displaywidth, 15*displaywidth, 40*displaywidth, 40*displaywidth) ImageName:@"morenFace"];
        if (_model.userheadImg.length > 0)
        {
            [faceView sd_setImageWithURL:URL(_model.userheadImg) placeholderImage:IMAGE(@"morenFace")];
        }
        faceView.contentMode = UIViewContentModeScaleAspectFill;
        faceView.layer.masksToBounds = YES;
        [whiteView addSubview:faceView];
        UILabel *nameLab = [ZCControl createLabelWithFrame:CGRectMake(65*displaywidth, 15*displaywidth, SCREEN_WIDTH- 100*displaywidth, 25*displaywidth) Font:15.0 Text:_model.username Color:RGB(51, 51, 51)];
        nameLab.lineBreakMode = NSLineBreakByTruncatingTail;
        nameLab.adjustsFontSizeToFitWidth = NO;
        [whiteView addSubview:nameLab];
        NSString *userCarNum = @"0";
        if (![_model.usercargoCount isEqualToString:@""])
        {
            userCarNum = _model.usercargoCount;
        }
        UILabel *phoneLab = [ZCControl createLabelWithFrame:CGRectMake(65*displaywidth, 40*displaywidth, SCREEN_WIDTH-90*displaywidth, 25*displaywidth) Font:13.0 Text:[NSString stringWithFormat:@"手机号：%@   发货%@条",_model.userphone,userCarNum] Color:RGB(153, 153, 153)];
        [whiteView addSubview:phoneLab];
        
    }
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 2)
    {
        PersonalHomePageViewController *vc = [[PersonalHomePageViewController alloc] init];
        vc.userid = s_str(_model.userid);
        [self.navigationController pushViewController:vc animated:YES];
    }
}


- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 2)
    {
        return 80*displaywidth;
    }
    else if (indexPath.section == 1 && indexPath.row == 2)
    {
        CGRect bounds = [string(@"备注：", _model.remark) boundingRectWithSize:CGSizeMake(SCREEN_WIDTH-60*displaywidth, 2000*displaywidth) options:NSStringDrawingUsesLineFragmentOrigin attributes:[NSDictionary dictionaryWithObject:NormalFontWithSize(13.0+fontScale) forKey:NSFontAttributeName] context:nil];
        CGFloat h = 85*displaywidth;
        if (bounds.size.height > 30*displaywidth)
        {
            h = 50*displaywidth+bounds.size.height+10*displaywidth;
        }
        h+=50*displaywidth;
        return 150*displaywidth;
    }
    return 50*displaywidth;
}

- (void)requestSuppHallList
{
    WEAKSELF;
    NSDictionary *dic = @{@"id":_idstr};
    [HYBaseHandler requestWithTheFormUrl:SERVER_cargoSelect Parmers:dic Success:^(id obj) {
        if ([obj server_Getcodecheck])
        {
//            NSArray *hallAry = [HallModel mj_objectArrayWithKeyValuesArray:obj[@"data"][@"content"]];
            _model = [HallModel mj_objectWithKeyValues:obj[@"data"]];
            if (_model.userheadImg.length > 0)
            {
                logoimage = [UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:_model.userheadImg]]];
                [logoimage jkr_compressToDataLength:3200 withBlock:^(NSData *data) {
                    UIImage *imageOne = [UIImage imageWithData:data];
                    logoimage = imageOne;
                }];
            }
            
            dispatch_async(dispatch_get_main_queue(), ^{
                [weakSelf.tableview reloadData];
            });
        }
        else
        {
            [LTools showMBProgressWithText:obj[@"msg"] addToView:weakSelf.view];
        }
    } failed:^(NSError *error) {
        [weakSelf.tableview.mj_header endRefreshing];
        [weakSelf.tableview.mj_footer endRefreshing];
    }];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (NSString *)timeIntervalFromLastTime:(NSString *)lastTime lastTimeFormat:(NSString *)format1
{
    //上次时间
    NSDateFormatter *dateFormatter1 = [[NSDateFormatter alloc]init];
    dateFormatter1.dateFormat = format1;
    NSDate *lastDate = [dateFormatter1 dateFromString:lastTime];
    //当前时间
    //    NSDateFormatter *dateFormatter2 = [[NSDateFormatter alloc]init];
    //    dateFormatter2.dateFormat = @"yyyy/MM/dd HH:mm:ss";
    //    NSDate *currentDate = [dateFormatter2 dateFromString:currentTime];
    return [self timeIntervalFromLastTime:lastDate ToCurrentTime:[NSDate date]];
    
}
- (NSString *)timeIntervalFromLastTime:(NSDate *)lastTime ToCurrentTime:(NSDate *)currentTime
{
    NSTimeZone *timeZone = [NSTimeZone systemTimeZone];
    //上次时间
    NSDate *lastDate = [lastTime dateByAddingTimeInterval:[timeZone secondsFromGMTForDate:lastTime]];
    //当前时间
    NSDate *currentDate = [currentTime dateByAddingTimeInterval:[timeZone secondsFromGMTForDate:currentTime]];
    //时间间隔
    NSInteger intevalTime = [currentDate timeIntervalSinceReferenceDate] - [lastDate timeIntervalSinceReferenceDate];
    
    //秒、分、小时、天、月、年
    NSInteger minutes = intevalTime / 60;
    NSInteger hours = intevalTime / 60 / 60;
    NSInteger day = intevalTime / 60 / 60 / 24;
    NSInteger month = intevalTime / 60 / 60 / 24 / 30;
    NSInteger yers = intevalTime / 60 / 60 / 24 / 365;
    
    if (minutes <= 10)
    {
        return  @"刚刚";
    }
    else if (minutes < 60)
    {
        return [NSString stringWithFormat: @"%ld分钟前",(long)minutes];
    }
    else if (hours < 24)
    {
        return [NSString stringWithFormat: @"%ld小时前",(long)hours];
    }else if (day < 30)
    {
        return [NSString stringWithFormat: @"%ld天前",(long)day];
    }else if (month < 12)
    {
        return [NSString stringWithFormat: @"%ld月前",(long)month];
    }
    else if (yers >= 1){
        return [NSString stringWithFormat: @"%ld年前",(long)yers];
    }
    return @"";
}
/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
